/**
 * Created by sxx on 2017/5/3.
 */
import "./index.less";
import bidHistoryListTpl from "./bid_history_list.handlebars";
import paginationTpl from "./paging.handlebars";
import httpurl from "../../../unit/common/js/httpurl";

let token = sessionStorage.getItem('supplier_token');
let projId = httpurl.uri.params.id;
let qotType = httpurl.uri.params.qotType;

Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};
var BidHistoryList = {
    pageNo: 1,
    pageSize: 20,
    maxPage: 1,
    isFirstPage: false,
    isLastPage: false,
    total: 0,

    init: function () {
        this.getData()
            .then(this.renderProduct)
            .then(this.renderPagination)
            .then(this.bindEvent);

    },

    // 获取数据
    getData: function(){
        return new Promise((resolve, reject)=>{
            let data = {
                "projId": projId,
                "qotTyp": qotType
            }
            let self = this;
                $.ajax({
                url: HOST_ADDR + `/cpmp/bidProjOnMngForSplr/getQotHis/${self.pageNo}/${self.pageSize}`,
                type: 'post',
                dataType: 'json',
                data: JSON.stringify(data),
                headers: {
                    'access_token': token,
                    'login_type': 'splr'
                },
                contentType:"application/json",
                success: function(resp){
                    if(resp.success){
                        self.total = resp.data.count;
                        self.isFirstPage = self.pageNo===1;
                        self.maxPage = Math.ceil(self.total/self.pageSize);
                        if(self.pageNo * self.pageSize >= self.total){
                            self.isLastPage = true;
                        }else{
                            self.isLastPage = false;
                        }

                        resolve(resp.data);
                    }
                    else{
                        console.log(resp.msgInf);
                    }
                },
                error:function(err){
                    console.log(err);
                }
            });

        });
    },

    // 渲染产品列表
    renderProduct: function(resp){

        // 处理数据

        $.each(resp.list,function(index,item){
            if (item.crtTim != null&&item.crtTim !='') {
                item.crtTimFmt = (new Date(item.crtTim)).Format("yyyy-MM-dd hh:mm:ss");
            } else {
                item.crtTimFmt = '';
            }
            item.qotTypFmt = item.qotType==="1"?"二次报价":"一次报价"
        });

        let listHtml = bidHistoryListTpl({bidHistoryList: resp.list});

        $('.J_product-list').html(listHtml);
    },

    renderPagination: function(){
        let self = BidHistoryList;
        let pageList = [];
        for(let i=0; i<self.maxPage; i++){
            pageList.push({idx: i+1});
        }
        let paginationHtml = paginationTpl({
            begin: (self.pageNo-1) * self.pageSize + 1,
            end: self.isLastPage ? self.total : self.pageNo * self.pageSize,
            total: self.total,
            isLastPage: self.isLastPage,
            isFirstPage: self.isFirstPage,
            pageList: pageList

        });
        $('.J_pagination').html(paginationHtml);
        $('.page-item').each((index,item)=>{
            if($(item).data('index')===self.pageNo){
                console.log(this);
                $(item).addClass('active');
            }
        });
    },

    // 绑定事件
    bindEvent: function(){
        let self = BidHistoryList;
        $('.J_prev').unbind().click(function(){
            if(self.pageNo > 1){
                self.pageNo = self.pageNo -1;
                self.renderList();
            }
        });
        $('.J_next').unbind().click(function(){
            if(self.pageNo < self.maxPage){
                self.pageNo = self.pageNo + 1;
                self.renderList();
            }

        });
        $('.page-item').unbind().click(function(){
             let $item = $(this);

             if(!$item.hasClass('active')){
                 self.pageNo = $item.data('index');
                 self.renderList();
             }
        });
    },

    // 渲染列表
    renderList(){
        this.getData()
            .then(this.renderProduct)
            .then(this.renderPagination)
            .then(this.bindEvent);
    }

};

jQuery(document).ready(function() {
    App.init();
    BidHistoryList.init();

});